package com.commit.service.impl;

import com.commit.domain.Answer;
import com.commit.domain.Question;
import com.commit.domain.User;
import com.commit.mapper.UserMapper;
import com.commit.ownException.NotFoundException;
import com.commit.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author:zyh
 * @Time:2021-02-27-18:44
 * @email:1269231889@qq.com
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;


    @Override
    public void register(User user) {
        userMapper.insert(user);
    }

    @Override
    public User findByName(String loginName) {
        return userMapper.findByLoginName(loginName);
    }

    @Override
    public User findById(Integer id) {
        return userMapper.findById(id);
    }

    @Override
    public List<Question> allQuestion(String username) {
        if(findByName(username)==null){
            throw new NotFoundException("user不存在");
        }
        List<Question> questions = userMapper.allQuestion(username);
        if(questions==null||questions.isEmpty()){
            throw new NotFoundException("没有提问");
        }
        return questions;
    }

    @Override
    public List<Answer> allAnswer(String username) {
        if(findByName(username)==null){
            throw new NotFoundException("user不存在");
        }
        List<Answer> answers = userMapper.allAnswer(username);
        return  answers;
    }

    @Override
    public boolean accept(Integer id,Integer answerId,Integer questionId) {
        if(findById(id)==null){
            throw new NotFoundException("no user");
        }
        //判断是否有权限采纳
        User byId = findById(id);
        String username = byId.getUsername();
        List<Question> questions = allQuestion(username);
        boolean flag = false;
        if(questions==null||questions.isEmpty()){
            throw new NotFoundException("没有提问");
        }
        for(Question question:questions){
            if(question.getUserId()==byId.getId()){
                flag=true;
            }
        }
        userMapper.accept(id,answerId);
        userMapper.closed(questionId);
        return flag;
    }
}
